package com.ys;

import java.util.ArrayList;
import java.util.List;

/**
 * 2020-06-11 牙膏 15 2 生活用品 // 记录消费信息, 包括[时间, 物品名称, 单价, 数量, 类别]
 * @program: note
 * @description:
 * @author:
 * @create 2020-06-11 23:43
 **/
public class ConsumeRecordMapper {

    private static final String FILE = System.getProperty("user.dir")
            + System.getProperty("file.separator") + "data"
            + System.getProperty("file.separator") + "consume_record.txt";

    private static final String COLUMN_SEP = "\t";

    private static volatile boolean inited = false;

    public static void init() {
        if (inited) {
            return;
        }

        synchronized (ConsumeRecordMapper.class) {
            if (!inited) {
                String result = FileIOUtils.read(FILE);
                if (result.trim().equals("")) {
                    FileIOUtils.write(FILE, ConsumeRecord.getTitle(), false);
                }

                inited = true;
            }
        }
    }

    public static ConsumeRecord parseFromLine(String line) {
        String[] input = line.split(COLUMN_SEP);
        String time = input[0].trim();
        String name = input[1].trim();
        Double price = Double.parseDouble(input[2].trim());
        Integer num = Integer.parseInt(input[3].trim());
        String type = input[4].trim();

        return createRecord(time, name, price, num, type);
    }

    public static ConsumeRecord createRecord(String time, String name,
                                             Double price, Integer num, String type) {
        ConsumeRecord record = new ConsumeRecord();
        record.setTime(time);
        record.setName(name);
        record.setPrice(price);
        record.setNum(num);
        record.setType(type);
        return record;
    }

    public static List<ConsumeRecord> getAll() {
        List<ConsumeRecord> records = new ArrayList<>();
        FileIOUtils.readLines(FILE).stream()
                .forEach(line -> {
                    if (!line.trim().startsWith("#")) {
                        records.add(parseFromLine(line));
                    }
                });
        return records;
    }

    public static void save(ConsumeRecord record) {
        init();
        FileIOUtils.write(FILE, record.toString(), true);
    }
}
